import { Component, Input, OnInit } from '@angular/core';
import { environment } from '@env/environment';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { VolunteerService } from '../../volunteer/service/volunteer.service';
import { NzDrawerRef } from 'ng-zorro-antd/drawer';
import { SystemDictService } from '../../../system/dict/service/service.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import E from 'wangeditor';
import { BlogService } from '../service/blog.service';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styles: [],
})
export class BlogEditComponent implements OnInit {
  @Input()
  record: any;
  form: FormGroup;
  editor = new E('#content1');
  constructor(
    private service: BlogService,
    private fb: FormBuilder,
    private modal: NzDrawerRef,
    private dictService: SystemDictService,
    private message: NzMessageService,
  ) {
    this.form = this.fb.group({
      id: [null],
      title: [null, [Validators.required]],
      keyword: [null, [Validators.required]],
      description: [null, [Validators.required]],
    });
  }

  ngOnInit(): void {
    this.editor.config.uploadImgShowBase64 = true;
    if (this.record) {
      this.form.patchValue(this.record);
      this.editor.create();
      this.editor.txt.html(this.record.content);
    } else {
      this.editor.create();
    }
  }

  save() {
    const isValid = this.validate();
    if (!isValid) {
      this.message.create('error', ' 请填写必填内容！');
      return;
    }

    if (String(this.editor.txt.html()).length == 0) {
      this.message.create('error', ' 请填写必填内容！');
      return;
    }

    const postData = {
      ...this.form.value,
      content: String(this.editor.txt.html()),
    };

    this.service.submit(postData).subscribe(() => {
      this.close(true);
    });
  }

  close(fg?: boolean) {
    this.modal.close(fg);
  }

  validate() {
    for (const key in this.form.controls) {
      if (this.form.controls.hasOwnProperty(key)) {
        const element = this.form.controls[key];
        element.markAsDirty();
        element.updateValueAndValidity();
      }
    }
    return this.form.valid;
  }
}
